//
//  MTRecentlyViewController.swift
//  MT
//
//  Created by ooops on 2020/6/1.
//  Copyright © 2020 张强. All rights reserved.
//

import UIKit
import JXCategoryView
import JXPagingView
import MTCategory
import YPNavigationBarTransition
import JXSegmentedView
import RxSwift
import RxCocoa
import Result
import ZFPlayer

typealias ListStatusCallBack = ((Bool, Int) -> ())

extension MTLatestViewController: UICollectionViewDelegate, UICollectionViewDataSource {
    
    //MARK: UICollectionViewDataSource
    
    func numberOfSections(in collectionView: UICollectionView) -> Int {
        return 1
    }
    
    func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        // TODO:- Required Method
        return self.model != nil ? 1 : models.count
    }
    
    func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
        // TODO:- Required Method
        self.currentPlayingIndexPath = indexPath
        var model: HomeListDetailModel?
        if self.model != nil {
            model = self.model
        } else {
            model = self.models[indexPath.item]
        }
        
        let cell = collectionView.dequeueReusableCell(withReuseIdentifier: MTHomeDouYinNoVideoCell.reuseIdentity(), for: indexPath) as! MTHomeDouYinNoVideoCell
        configureCell(cell: cell, forItemAt: indexPath)
        cell.model = model
        self.playControlView.show(cover: model?.imgs?.first?.href, imageMode: .scaleAspectFill)
        cell.delegate = self
        //cell.hiddenInfo(isHidden: self.model == nil)
        return cell
    }
    
    func configureCell(cell: UICollectionViewCell, forItemAt indexPath: IndexPath) {
        
    }
    
    //MARK: UICollectionViewDelegate
    
    func scrollViewDidScroll(_ scrollView: UIScrollView) {
        self.player.currentPlayerManager.pause?()
        scrollView.zf_scrollViewDidScroll()
        self.listViewDidScrollCallback?(scrollView)
    }
    
    func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
//        if self.model != nil {
//            self.playTheVideo(at: indexPath, scrollToTop: false)
//            return
//        }
//        let vc = MTLatestViewController()
//        let model = self.models[indexPath.item]
//        vc.model = model
//        self.navigationController?.pushViewController(vc, animated: true)
    }
    
    func collectionView(_ collectionView: UICollectionView, didDeselectItemAt indexPath: IndexPath) {
        
    }
    
    func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize {
        if self.model != nil {
            return CGSize(width: ScreenWidth, height: ScreenHeight)
        }
        return CGSize(width: ScreenWidth, height: ScreenHeight - TabBarHeight)
    }
    
    func scrollViewDidEndDecelerating(_ scrollView: UIScrollView) {
        scrollView.zf_scrollViewDidEndDecelerating()
        let scrollToScrollStop = !scrollView.isTracking && !scrollView.isDragging && !scrollView.isDecelerating
        if scrollToScrollStop {
            DispatchQueue.main.after(0.26) {
                self.scrollViewDidEndScroll()
            }
        }
    }
    /// 计算scrollView停止滚动的方法
    private func scrollViewDidEndScroll() {
        //if self.model == nil { return }
        if let indexPath = self.collectionView.indexPathsForVisibleItems.first {
            resetControlView(at: indexPath)
//            if indexPath == self.currentPlayingIndexPath {
            if self.player.currentPlayerManager.playState == ZFPlayerPlaybackState.playStatePaused, indexPath == self.player.playingIndexPath {
                DispatchQueue.main.after(0.26) {
                    self.player.currentPlayerManager.play?()
                }
                return
            }
//                return
//            }
            if let m = self.urls?[indexPath.item], m.absoluteString != "https://" {
                DispatchQueue.main.after(0.25) {
                    self.player.playTheIndexPath(indexPath, assetURL: m, scrollToTop: false)
                }
            } else {
                self.player.stopCurrentPlayingCell()
            }
            /// 预加载数据
            if indexPath.item > self.models.count - 10 {
                loadMore()
            }
        }
    }
    
    func scrollViewDidEndDragging(_ scrollView: UIScrollView, willDecelerate decelerate: Bool) {
        scrollView.zf_scrollViewDidEndDraggingWillDecelerate(decelerate)
        if decelerate == false {
            scrollViewDidEndDecelerating(scrollView)
        }
    }
    
    func scrollViewDidScrollToTop(_ scrollView: UIScrollView) {
        self.listViewDidScrollCallback?(scrollView)
        scrollView.zf_scrollViewDidScroll()
    }
    
    func scrollViewWillBeginDragging(_ scrollView: UIScrollView) {
        scrollView.zf_scrollViewWillBeginDragging()
    }
    
    private func playTheVideo(at indexPath: IndexPath, scrollToTop: Bool) {
        //if self.model == nil { return }
        if self.urls?.count == 0 {
            return
        }
        
        var url: URL?
        if indexPath.item >= self.urls?.count ?? 0 {
            url = self.urls?.last
        } else {
            url = self.urls?[indexPath.item]
        }
        
        if let m = url {
            //debugPrint(m.absoluteString)
            if m.absoluteString == "https://" {
                self.player.stopCurrentPlayingCell()
                return
            }
            self.player.addPlayerViewToCell()
            DispatchQueue.main.after(0.25) {
                self.player.playTheIndexPath(indexPath, assetURL: m, scrollToTop: false)
            }
        }
        resetControlView(at: indexPath)
    }
    /// 重置控制层
    private func resetControlView(at indexPath: IndexPath) {
        /// 控制层
        self.playControlView.resetControlView()
        if let vo = self.model, let img = vo.imgs?.first?.href {
            //debugPrint("--------", img)
            self.playControlView.show(cover: img, imageMode: .scaleAspectFill)
        } else {
            
            var model: HomeListDetailModel?
            if indexPath.item >= self.urls?.count ?? 0 {
                model = self.models.last
            } else {
                model = self.models[indexPath.item]
            }
            
            if let vo = model, let img = vo.imgs?.first?.href {
                //debugPrint(img)
                self.playControlView.show(cover: img, imageMode: .scaleAspectFill)
            }
        }
    }
    
}

extension MTLatestViewController {
    
    public func setGenderType(_ genderType: LocalGenderModel.GenderType, isCurrentPagingController: Bool) {
        displayGenderType = genderType
        reloadAllData { [weak self] in
            guard let weakSelf = self else { return }
            if !isCurrentPagingController {
                weakSelf.player.currentPlayerManager.pause?()
            }
        }
    }
    
    /// 数据请求
    private func dataRequest(isAppendingDatas: Bool = false, completion: (() -> Swift.Void)? = nil) {
        if self.model != nil { return }
        provider.rx.requestResult(requestTarget).subscribe(onNext: { [weak self] (result: Result<HomeListDetailReponseModel, AnyError>, isCache: Bool) in
            guard let weakSelf = self else { return }
            weakSelf.collectionView.mj_header?.endRefreshing()
            weakSelf.collectionView.mj_footer?.endRefreshing()
            
            switch result {
            case .success(let model):
                if weakSelf.currentPage > model.page?.pages ?? 0 {
                    weakSelf.collectionView.mj_footer?.endRefreshingWithNoMoreData()
                    return
                }
                weakSelf.currentPage += 1
                if let result = model.result {
                    if isAppendingDatas {
                        weakSelf.models += result
                    } else {
                        //weakSelf.collectionView.player.stopCurrentPlayingCell()
                        weakSelf.models.removeAll()
                        weakSelf.urls?.removeAll()
                        weakSelf.models = result
                        //weakSelf.collectionView.playVideo(at: IndexPath(row: 0, section: 0), scrollToTop: false)
                    }
                    /// 构建播放视频的url资源
                    for(_, v) in result.enumerated() {
                        if v.isContainVideo, let href = v.imgs?[1].href {
                            weakSelf.urls?.append(URL(string: href)!)
                        } else {
                            weakSelf.urls?.append(URL(string: "https://")!)
                        }
                    }
                }
                /// 播放第一个视频
                if weakSelf.models.count <= 10 {
                    DispatchQueue.main.after(0.25) {
                        weakSelf.playTheVideo(at: IndexPath(item: 0, section: 0), scrollToTop: true)
                    }
                }
                break
                
            case .failure(_):
                break
                
            }
            
            if let completion = completion {
                completion()
            }
            
        }).disposed(by: globalDisposedBag)
    }
    
}

class MTLatestViewController: BaseViewController {
    /// 是否已经提示过, 点赞需要消耗钻石
    private var isNoticeLikeTip: Bool = false
    /// 充当详情的显示设置次model
    var model: HomeListDetailModel?
    /// 当前播放的indexPath
    var currentPlayingIndexPath: IndexPath?
    /// 列表展示性别 - 默认为不限
    var displayGenderType: LocalGenderModel.GenderType = .unknown
    /// 当前页数
    var currentPage: Int = 1
    var urls: [URL]? = []
    var player: ZFPlayerController!
    /// 请求类型
    private var requestTarget: HomeApi {
        switch dataDisplayType {
        case .hottest:
            return displayGenderType == .unknown ? .hotListWithoutGender(curPage: currentPage) : .hotList(curPage: currentPage, sex: displayGenderType.requestType)
        case .latest:
            return displayGenderType == .unknown ? .latestListWithoutGender(curPage: currentPage) : .latestList(curPage: currentPage, sex: displayGenderType.requestType)
        }
    }
    /// 列表展示模型
    var models: [HomeListDetailModel] = [] {
        didSet {
            collectionView.reloadData()
        }
    }
    
    /// 重新加载所有数据
    public func reloadAllData(completion: (() -> Swift.Void)? = nil) {
        currentPage = 1
        //models = []
        dataRequest(completion: completion)
    }
    
    /// 展示数据类型
    var dataDisplayType: NewDataDisplayType = .hottest {
        didSet {
            //tableView.type = dataDisplayType.rawValue
            reloadAllData()
        }
    }
    
    @objc public func loadMore() {
        dataRequest(isAppendingDatas: true)
    }
    
    @objc public func loadFirst() {
        currentPage = 1
        reloadAllData()
    }
    
    public var listViewDidScrollCallback: ((UIScrollView) -> ())?
    //private var listStatusCallBack: ListStatusCallBack?
    /// MTProvider
    private lazy var provider: MTProvider<HomeApi> = {
        return MTProvider<HomeApi>(plugins: [])
    }()
    
//    convenience init(callback: @escaping ListStatusCallBack) {
//        self.init()
//        self.listStatusCallBack = callback
//    }
    
    convenience init(model: HomeListDetailModel?) {
        self.init()
        self.model = model
    }
    
    override func viewWillDisappear(_ animated: Bool) {
        super.viewWillDisappear(animated)
        self.player.currentPlayerManager.pause?()
    }
    
    override func viewWillAppear(_ animated: Bool) {
        super.viewWillAppear(animated)
        DispatchQueue.main.after(0.25) {
            self.resetControlView(at: IndexPath(item: self.player.currentPlayIndex, section: 0))
            self.player.currentPlayerManager.play?()
        }
    }
    
    override func viewDidDisappear(_ animated: Bool) {
        super.viewDidDisappear(animated)
        self.player.currentPlayerManager.pause?()
    }

    override func viewDidLoad() {
        super.viewDidLoad()
        
        let playerManager = ZFAVPlayerManager()
        playerManager.scalingMode = ZFPlayerScalingMode.aspectFill
        
        self.player = ZFPlayerController.player(with: self.collectionView, playerManager: playerManager, containerViewTag: 100)
        self.player.controlView = self.playControlView
        self.player.disableGestureTypes = [.pinch, .pan]
        self.player.isWWANAutoPlay = true
        
        /// 播完重播
        self.player.playerDidToEnd = { [weak self] asset in
            guard let weakSelf = self else { return }
            weakSelf.player.currentPlayerManager.replay?()
        }

        view.addSubview(collectionView)
        
        if #available(iOS 11,*) {
            collectionView.contentInsetAdjustmentBehavior = .never
        } else {
            self.automaticallyAdjustsScrollViewInsets = false
        }
        
        if self.model != nil {
            collectionView.snp.makeConstraints { (make) in
                make.top.left.right.equalToSuperview()
                //make.bottom.equalToSuperview().offset(-TabBarHeight)
                make.height.equalToSuperview()
            }
            if let v = model, v.isContainVideo, let href = v.imgs?[1].href {
                self.urls?.append(URL(string: href)!)
                DispatchQueue.main.after(0.25) {
                    self.playTheVideo(at: IndexPath(item: 0, section: 0), scrollToTop: true)
                }
            } else {
                self.urls?.append(URL(string: "https://")!)
            }
            
            self.collectionView.mj_header = nil
            self.collectionView.mj_footer = nil
            self.collectionView.isPagingEnabled = false
            self.collectionView.isScrollEnabled = false
            collectionView.reloadData()
            DispatchQueue.main.after(0.25) {
                self.playTheVideo(at: IndexPath(item: 0, section: 0), scrollToTop: true)
            }
            return
        } else {
            collectionView.snp.makeConstraints { (make) in
                make.top.left.right.equalToSuperview()
                //make.bottom.equalToSuperview().offset(-TabBarHeight)
                make.height.equalTo(ScreenHeight - TabBarHeight)
            }
        }
        
        
        reloadAllData()
        NotificationCenter.default.addObserver(self, selector: #selector(MTLatestViewController.didBecomeFriend(notification:)), name: GlobalNotificationName.didBecomeFriend.name, object: nil)
        NotificationCenter.default.addObserver(self, selector: #selector(MTLatestViewController.didRevokeFriend(notification:)), name: GlobalNotificationName.didRevokeFriend.name, object: nil)
    }
    
    deinit {
        NotificationCenter.default.removeObserver(self)
    }
    
    /// 成功删除好友后, 刷新界面
    @objc private func didRevokeFriend(notification: Notification) {
        if let userInfo = notification.userInfo, let userName = userInfo["userName"] as? String {
            for(_, v) in self.models.enumerated() {
                if v.userName == userName {
                    v.isFriend = false
                    self.collectionView.reloadData()
                    break
                }
            }
         }
    }
    
    /// 成功添加好友后, 刷新界面
    @objc private func didBecomeFriend(notification: Notification) {
        if let userInfo = notification.userInfo, let userName = userInfo["userName"] as? String {
            for(_, v) in self.models.enumerated() {
                if v.userName == userName {
                    v.isFriend = true
                    self.collectionView.reloadData()
                    break
                }
            }
         }
    }
    
    lazy var collectionView: UICollectionView = {
        /// 设置大小
        let flowLayout = UICollectionViewFlowLayout()
        flowLayout.itemSize = CGSize(width: ScreenWidth, height: self.model == nil ? ScreenHeight - TabBarHeight : ScreenHeight)
        flowLayout.minimumInteritemSpacing = CGFloat.leastNonzeroMagnitude
        flowLayout.minimumLineSpacing = CGFloat.leastNonzeroMagnitude
        let cv = UICollectionView(frame: CGRect(x: 0, y: 0, width: ScreenWidth, height: self.model == nil ? ScreenHeight - TabBarHeight : ScreenHeight), collectionViewLayout: flowLayout)
        cv.backgroundColor = UIColor.common.x161616
        cv.showsVerticalScrollIndicator = false
        cv.delegate = self
        cv.dataSource = self
        cv.scrollsToTop = false
        cv.showsHorizontalScrollIndicator = false
        cv.isPagingEnabled = true
        cv.register(MTHomeDouYinCell.self, forCellWithReuseIdentifier: MTHomeDouYinCell.reuseIdentity())
        cv.register(MTHomeDouYinNoVideoCell.self, forCellWithReuseIdentifier: MTHomeDouYinNoVideoCell.reuseIdentity())
        cv.emptySetView = ViewFactory.emptySetView { [weak self] in
            guard let weakself = self else { return }
            weakself.dataRequest(isAppendingDatas: false, completion: nil)
        }
        cv.mj_footer = ViewFactory.normalFooter(target: self, selector: #selector(loadMore))
        cv.mj_header = ViewFactory.normalHeader(target: self, selector: #selector(loadFirst))
        return cv
    }()
    
    lazy var controlView: ZFPlayerControlView = {
        let v = ZFPlayerControlView()
        return v
    }()
    
    lazy var playControlView: MTHomePlayControlView = {
        let v = MTHomePlayControlView()
        return v
    }()
    

}

extension MTLatestViewController: JXSegmentedListContainerViewListDelegate {
    func listViewDidScrollCallback(callback: @escaping (UIScrollView) -> ()) {
        listViewDidScrollCallback = callback
    }


    func listView() -> UIView {
        return self.view
    }

    func listScrollView() -> UIScrollView {
        return self.collectionView
    }
    
    func listWillDisappear() {
        self.player.currentPlayerManager.pause?()
        //self.listStatusCallBack?(true, 2)
    }
    
    func listWillAppear() {
        //self.listStatusCallBack?(false, 2)
        self.player.currentPlayerManager.play?()
    }
}

extension MTLatestViewController: MTHomeDouYinNoVideoCellDelegate {
    func likeEvent(cell: MTHomeDouYinNoVideoCell, goodButton: GKLikeView, model: HomeListDetailModel?) {
        if !isNoticeLikeTip {
            UIAlertController.rx.show(in: self, title: "提示", message: "点赞需要消耗1钻石", buttons: [.cancel("取消"), .default("确定")]).subscribe(onSuccess: { [weak self] index in
                guard let weakSelf = self else { return }
                /// 去充值的引导
                if index == 1 {
                    weakSelf.isNoticeLikeTip = true
                    weakSelf.privateLikeEvent(cell: cell, goodButton: goodButton, model: model)
                }
            })
            .disposed(by: globalDisposedBag)
            return
        }
        
        privateLikeEvent(cell: cell, goodButton: goodButton, model: model)
        
    }
    
    private func privateLikeEvent(cell: MTHomeDouYinNoVideoCell, goodButton: GKLikeView, model: HomeListDetailModel?) {
        guard let trendId = model?.lastTrendId else { return }
        provider.rx.requestResult(.realTrendsLike(trendId: trendId)).subscribe(onNext: { (result:Result<HomeLikeComponentModel, AnyError> , isCache:Bool) in
            switch result {
            case .success(let listModel):
                if listModel.code == 200 {
                    DispatchQueue.main.async {
                        model?.selfLike = 1
                        goodButton.setupLikeCount("\(listModel.result)")
                        goodButton.startAnimation(withIsLike: true, canHit: true)
                    }
                }
                /// 用户余额不足
                if listModel.code == 600 {
                    UIAlertController.rx.show(in: self, title: "提示", message: "点赞需要消耗1钻石，钻石不足，请充值", buttons: [.cancel("取消"), .default("去充值")]).subscribe(onSuccess: { index in
                        /// 去充值的引导
                        if index == 1 {
                            if UserDefaults.AppValidate.isValidate.storedBool == false {
                                let c = MTPaymentViewController()
                                self.navigationController?.pushViewController(c, animated: true)
                            } else {
                                let c = MTInAppPurchasesViewController()
                                self.navigationController?.pushViewController(c, animated: true)
                            }
                        }
                    })
                    .disposed(by: globalDisposedBag)
                }
            case .failure(_):
                break
            }
            
        }).disposed(by: globalDisposedBag)
    }
    
    func addFriend(cell: MTHomeDouYinNoVideoCell, model: HomeListDetailModel?, sender: UIButton) {
        if let un = model?.userName {
            self.presentGiftView(isFriend: false, imUserName: un, didClickRechargeCallBack: { [weak self] in
                guard let weakself = self else { return }
                if UserDefaults.AppValidate.isValidate.storedBool == false {
                    let c = MTPaymentViewController()
                    weakself.navigationController?.pushViewController(c, animated: true)
                } else {
                    let c = MTInAppPurchasesViewController()
                    weakself.navigationController?.pushViewController(c, animated: true)
                }
                }, selectedGiftCallBack: { [weak self] (model, count) in
                    
            }, didClickSayHiCallBack: { [weak self] (model, count) in
                guard let weakself = self else { return }
                let c = MTAddFriendViewController(giftCount: count, targetUserName: un, giftModel: model)
                weakself.navigationController?.pushViewController(c, animated: true)
            }) {
                
            }
        }
    }
    
    func entrancePersonal(cell: MTHomeDouYinNoVideoCell, model: HomeListDetailModel?) {
        guard let userName = model?.userName else { return }
        let c = MineViewController(username: userName)
        navigationController?.pushViewController(c, animated: true)
    }
    
    func black(userId: Int) {
        provider.rx.requestResult(.moment(blackUserId: userId)).subscribe(onNext: { (result: Result<MineInfoListResponseModel, AnyError>, isCache: Bool) in
            switch result {
            case let .success(response):
                if response.code == 200 {
                    for (i, v) in self.models.enumerated() {
                        if let un = v.id, un == userId {
                            self.models.remove(at: i)
                            DispatchQueue.main.async {
                                self.collectionView.reloadData()
                            }
                            break
                        }
                        continue
                    }
                }
                break
                
            case .failure(_):
                break
            }
        }).disposed(by: globalDisposedBag)
    }
    
}

extension MTLatestViewController {
//    override func yp_navigationBarTintColor() -> UIColor! {
//        return UIColor(hex: 0xFFFFFF)
//    }

    override func yp_navigtionBarConfiguration() -> YPNavigationBarConfigurations {
        return [.backgroundStyleColor, .styleBlack, .backgroundStyleTransparent]
    }

//    override func yp_navigationBackgroundColor() -> UIColor! {
//        return UIColor(hex: 0x000000)
//    }
    
    override var preferredStatusBarStyle: UIStatusBarStyle {
        return .lightContent
    }
}
